package com.jn.gsondemo.views;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;

import com.jn.gsondemo.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class HotSearchActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hot_search);

        // 假设你已经从某个地方获取了hotsearch.json的字符串
        String hotSearchJsonString = getIntent().getStringExtra("hotsearch_json");

        try {
            JSONObject hotSearchJson = new JSONObject(hotSearchJsonString);
            JSONArray result = hotSearchJson.getJSONArray("result");

            List<String> hotSearchItems = new ArrayList<>();
            final List<String> links = new ArrayList<>();
            for (int i = 0; i < result.length(); i++) {
                JSONObject item = result.getJSONObject(i);
                String title = item.getString("title");
                String link = item.getString("link");
                hotSearchItems.add(title);
                links.add(link);
            }

            ListView hotSearchListView = findViewById(R.id.hot_search_list);
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, hotSearchItems);
            hotSearchListView.setAdapter(adapter);

            hotSearchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String url = links.get(position);
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
